package com.begye.smartloan.apptest.detailadsource

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.data.analysislib.AnalyticsUtil
import com.data.datalib.util.ASGeneralUtil
import com.begye.smartloan.apptest.ext.toThousandUnitFormat
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.doPostRequest
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.min

class DetailAdSourceViewModel : ViewModel() {

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _previewDetailLiveData = MutableLiveData<JSONObject>()
    val onPreviewDetailLiveData get() = _previewDetailLiveData

    private val _sliderChangedLiveData = MutableLiveData<String>()
    val onSliderChangedLiveData get() = _sliderChangedLiveData

    private val _calChangedLiveData = MutableLiveData<String>()
    val onCalChangedLiveData get() = _calChangedLiveData

    private val _shengQingSuccessfulLiveData = MutableLiveData<Boolean>()
    val onShengQingSuccessfulLiveData get() = _shengQingSuccessfulLiveData

    var decideJinE: String = "0"
    var decideDay: String = ""
    var decideMaxJinE: String = ""
    var decideMinJinE: String = ""

    fun requestPreviewDetail(localLanguage: String = "") {
        if(decideJinE.isBlank()){
            decideJinE = "0"
        }
        val params = hashMapOf<String, Any>().apply {
            put("amount", decideJinE)
            put("maxAmount", decideMaxJinE)
            put("minAmount", decideMinJinE)
            put("days", decideDay)
            put("localLanguage", localLanguage)
        }
        doPostRequest(
            path = "/ppfdacoetuei37843Pdfje",
            action = params,
            loading = _loadingStateLiveData,
            object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                        decideDay = obj.optString("days", "")
                        decideJinE = obj.optString("amount", "0").toFloat().toInt().toString()
                        if(decideJinE.isBlank()){
                            decideJinE = "0"
                        }

                        // slider value
                        val chooseAmountFlag = obj.optBoolean("chooseAmountFlag", false)
                        if (chooseAmountFlag) {
                            val curjinE = obj.optString("amount", "0").toFloat()
                            val maxjinE = obj.optString("maxAmount", "0").toFloat()
                            var process: Float = 0F
                            if (maxjinE > 0) {
                                process = (curjinE / maxjinE) * 100F
                                process = min(process, 100F)
                                obj.put("processFormat", process.toString())
                            }

                            decideMaxJinE = obj.optString("maxAmount", "")
                            decideMaxJinE = obj.optString("minAmount", "")

                        } else {
                            decideMaxJinE = ""
                            decideMinJinE = ""
                        }

                        obj.put("amountFormat", obj.optString("amount", "").toThousandUnitFormat())
                        obj.put(
                            "minAmountFormat",
                            obj.optString("minAmount", "").toThousandUnitFormat()
                        )
                        obj.put(
                            "maxAmountFormat",
                            obj.optString("maxAmount", "").toThousandUnitFormat()
                        )

                        // format days list
                        val daysArray = obj.optJSONArray("daysArray") ?: JSONArray()
                        val currentDay = obj.optString("days", "")
                        val dasArrayFormat = JSONArray()
                        for (index in 0 until daysArray.length()) {
                            val day = daysArray.optString(index, "")
                            if (day.isNotBlank()) {
                                val item = JSONObject().apply {
                                    put("day", day)
                                    put("isChecked", day == currentDay)
                                }
                                dasArrayFormat.put(item)
                            }
                        }

                        // if not days list, initials default day
                        if (dasArrayFormat.length() == 0) {
                            val item = JSONObject().apply {
                                put("day", currentDay)
                                put("isChecked", true)
                            }
                            dasArrayFormat.put(item)
                        }
                        obj.put("dasArrayFormat", dasArrayFormat)

                        // items array
                        val detailItemList = obj.optJSONArray("detailItemList") ?: JSONArray()

                        // 找到第一个和第二个 "YES" 索引
                        var firstYesFound = false
                        var secondYesIndex = -1
                        for (i in 0 until detailItemList.length()) {
                            val item = detailItemList.getJSONObject(i)
                            if (item.optString("title") == "YES") {
                                if (firstYesFound) {
                                    secondYesIndex = i
                                    break
                                } else {
                                    firstYesFound = true
                                }
                            }
                        }

                        // 分割 JSONArray
                        val itemArray1 = JSONArray()
                        val itemArray2 = JSONArray()

                        for (i in 0 until secondYesIndex) {
                            itemArray1.put(detailItemList.getJSONObject(i))
                        }
                        for (i in secondYesIndex until detailItemList.length()) {
                            itemArray2.put(detailItemList.getJSONObject(i))
                        }
                        obj.put("itemArray1", itemArray1)
                        obj.put("itemArray2", itemArray2)

                        _previewDetailLiveData.value = obj

                    } catch (e: Exception) {
                        //
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun requestConfirmShenQing() {
        if(decideJinE.isBlank()){
            decideJinE = "0"
        }
        val params = hashMapOf<String, Any>().apply {
            put("amount", decideJinE)
            put("days", decideDay)
            put("language", ASGeneralUtil.getLanguage())
        }
        doPostRequest(
            path = "/iMdcl0soO3dnJ59RIw9hag",
            action = params,
            loading = _loadingStateLiveData,
            object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        AnalyticsUtil.addApplyEvent()

                        _shengQingSuccessfulLiveData.value = true
                    } catch (e: Exception) {
                        //
                        _shengQingSuccessfulLiveData.value = false
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }

    fun calSliderChanged(process: Float, isSliding: Boolean = true) {
        try {
            _previewDetailLiveData.value?.let { result ->
                println(result)
                val jinE = result.optString("minAmount", "0").toFloat()
                val minJinE = result.optString("minAmount", "0")
                val maxJinE = result.optString("maxAmount", "0")

                // ke li du
                val granularity = result.optString("granularity", "0").toFloat().toInt()
                if (granularity <= 0) return

                val edgeJinE = maxJinE.toFloat() - minJinE.toFloat()
                val needAddJinE = (edgeJinE * process / 100F).toInt()
                val scale = (((jinE + needAddJinE) / granularity).toInt()) * granularity
                val resultJinEFormat = scale.toString().toThousandUnitFormat()

                decideJinE = scale.toString()
                if(decideJinE.isBlank()){
                    decideJinE = "0"
                }
                _sliderChangedLiveData.value = resultJinEFormat

                if (isSliding) return
                _calChangedLiveData.value = resultJinEFormat
            }
        } catch (e: Exception) {
            //
            e.printStackTrace()
        }
    }

    fun updateDayFromPosition(position: Int) {
        try {
            _previewDetailLiveData.value?.let { result ->
                println(result)
                val daysArray = result.optJSONArray("daysArray") ?: JSONArray()
                if (daysArray.length() > position) {
                    val day = daysArray.optString(position)
                    decideDay = day.toFloat().toInt().toString()
                }
            }
        } catch (e: Exception) {
            //
            e.printStackTrace()
        }
    }
}